package com.example.votemanage.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.votemanage.entity.Auction;
import com.example.votemanage.entity.AuctionRecord;
import com.example.votemanage.entity.AuctionUser;
import com.example.votemanage.mapper.AuctionMapper;
import com.example.votemanage.mapper.AuctionRecordMapper;
import com.example.votemanage.mapper.AuctionUserMapper;
import com.example.votemanage.service.AuctionRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AuctionRecordServiceImpl extends ServiceImpl<AuctionRecordMapper, AuctionRecord> implements AuctionRecordService {
    @Autowired
    private AuctionMapper auctionMapper;

    @Autowired
    private AuctionRecordMapper auctionRecordMapper;

    @Autowired
    private AuctionUserMapper auctionUserMapper;

    public Page<AuctionRecord> getAuctionRecordWithDetails(int page, int size) {
        Page<AuctionRecord> recordPage = new Page<>(page, size);
        QueryWrapper<AuctionRecord> wrapper = new QueryWrapper<>();
        Page<AuctionRecord> paginatedRecords = auctionRecordMapper.selectPage(recordPage, wrapper);

        List<Integer> userIds = paginatedRecords.getRecords().stream().map(AuctionRecord::getUserId).collect(Collectors.toList());
        List<Integer> auctionIds = paginatedRecords.getRecords().stream().map(AuctionRecord::getAuctionId).collect(Collectors.toList());

        if (userIds.isEmpty() || auctionIds.isEmpty()) {
            return new Page<>(page, size);
        }

        List<AuctionUser> users = auctionUserMapper.selectBatchIds(userIds);
        List<Auction> auctions = auctionMapper.selectBatchIds(auctionIds);

        for (AuctionRecord record : paginatedRecords.getRecords()) {
            record.setUser(users.stream().filter(u -> u.getUserId()==(record.getUserId())).findFirst().orElse(null));
            record.setAuction(auctions.stream().filter(a -> a.getAuctionId().equals(record.getAuctionId())).findFirst().orElse(null));
        }

        return paginatedRecords;
    }

    public List<AuctionRecord> getAuctionRecord(Integer auctionId) {
        // 构建查询条件，根据拍品ID获取拍卖记录
        QueryWrapper<AuctionRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("auctionId", auctionId);
        List<AuctionRecord> records = auctionRecordMapper.selectList(queryWrapper);
        if (records.isEmpty()) {
            return Collections.emptyList(); // 没有记录则直接返回空列表
        }
        // 根据用户ID分组并找出每个用户最高的拍卖记录
        Map<Integer, Optional<AuctionRecord>> highestRecordsByUser = records.stream()
                .collect(Collectors.groupingBy(
                        AuctionRecord::getUserId,
                        Collectors.maxBy(Comparator.comparing(AuctionRecord::getAuctionPrice))
                ));
        // 将非空的最高拍卖记录转换为一个列表
        List<AuctionRecord> highestRecords = highestRecordsByUser.values().stream()
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());
        if (highestRecords.isEmpty()) {
            return highestRecords; // 没有最高记录则直接返回空列表
        }
        // 获取记录中的所有用户ID和拍卖ID
        List<Integer> userIds = highestRecords.stream().map(AuctionRecord::getUserId).collect(Collectors.toList());
        List<Integer> auctionIds = highestRecords.stream().map(AuctionRecord::getAuctionId).collect(Collectors.toList());
        // 根据用户ID和拍卖ID分别查询用户和拍卖详情
        List<AuctionUser> users = auctionUserMapper.selectBatchIds(userIds);
        List<Auction> auctions = auctionMapper.selectBatchIds(auctionIds);
        // 将查询结果整合到拍卖记录中
        for (AuctionRecord record : highestRecords) {
            record.setUser(users.stream().filter(u -> u.getUserId()==(record.getUserId())).findFirst().orElse(null));
            record.setAuction(auctions.stream().filter(a -> a.getAuctionId().equals(record.getAuctionId())).findFirst().orElse(null));
        }
        return highestRecords;
    }
    public List<AuctionRecord> selectRecordMax() {
        // 获取所有拍卖记录
        List<AuctionRecord> records = auctionRecordMapper.selectList(null);
        // 时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime currentDateTime = LocalDateTime.now(); // 当前时间
        // 根据拍品ID分组，并找出每个拍品的最高拍卖记录，同时过滤掉尚未结束的拍卖
        Map<Integer, Optional<AuctionRecord>> highestRecordsByAuction = records.stream()
                .filter(record -> {
                    Auction auction = auctionMapper.selectById(record.getAuctionId());
                    if (auction == null) return false;
                    LocalDateTime auctionEndTime = LocalDateTime.parse(auction.getAuctionEndTime(), formatter);
                    return auctionEndTime.isBefore(currentDateTime);
                })
                .collect(Collectors.groupingBy(
                        AuctionRecord::getAuctionId,
                        Collectors.maxBy(Comparator.comparing(AuctionRecord::getAuctionPrice))
                ));
        // 将非空的最高拍卖记录转换为一个列表
        List<AuctionRecord> highestRecords = highestRecordsByAuction.values().stream()
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());

        if (highestRecords.isEmpty()) {
            return highestRecords; // 没有最高记录则直接返回空列表
        }
        // 获取记录中的所有用户ID和拍卖ID
        List<Integer> userIds = highestRecords.stream().map(AuctionRecord::getUserId).collect(Collectors.toList());
        List<Integer> auctionIds = highestRecords.stream().map(AuctionRecord::getAuctionId).collect(Collectors.toList());
        // 根据用户ID和拍卖ID分别查询用户和拍卖详情
        List<AuctionUser> users = auctionUserMapper.selectBatchIds(userIds);
        List<Auction> auctions = auctionMapper.selectBatchIds(auctionIds);
        // 将查询结果整合到拍卖记录中
        for (AuctionRecord record : highestRecords) {
            record.setUser(users.stream().filter(u -> u.getUserId() == record.getUserId()).findFirst().orElse(null));
            record.setAuction(auctions.stream().filter(a -> a.getAuctionId().equals(record.getAuctionId())).findFirst().orElse(null));
        }
        return highestRecords;
    }
    public List<AuctionRecord> selectRecordMaxnext() {
        // 获取所有拍卖记录
        List<AuctionRecord> records = auctionRecordMapper.selectList(null);
        // 时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime currentDateTime = LocalDateTime.now(); // 当前时间
        // 根据拍品ID分组，并找出每个拍品的最高拍卖记录
        Map<Integer, Optional<AuctionRecord>> highestRecordsByAuction = records.stream()
                .filter(record -> {
                    Auction auction = auctionMapper.selectById(record.getAuctionId());
                    if (auction == null) return false;
                    LocalDateTime auctionStartTime = LocalDateTime.parse(auction.getAuctionStartTime(), formatter);
                    LocalDateTime auctionEndTime = LocalDateTime.parse(auction.getAuctionEndTime(), formatter);
                    // 过滤不在拍卖时间范围内的记录
                    return auctionStartTime.isBefore(currentDateTime) && auctionEndTime.isAfter(currentDateTime);
                })
                .collect(Collectors.groupingBy(
                        AuctionRecord::getAuctionId,
                        Collectors.maxBy(Comparator.comparing(AuctionRecord::getAuctionPrice))
                ));

        // 将非空的最高拍卖记录转换为一个映射关系，用于快速查找最高出价
        Map<Integer, AuctionRecord> highestRecordsMap = highestRecordsByAuction.values().stream()
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toMap(AuctionRecord::getAuctionId, record -> record));

        // 锁定最高出价记录的 ID
        Set<Integer> highestRecordIds = highestRecordsMap.values().stream()
                .map(AuctionRecord::getId)
                .collect(Collectors.toSet());

        // 过滤掉最高出价记录，并且是在拍卖时间范围内的记录
        List<AuctionRecord> nonHighestActiveRecords = records.stream()
                .filter(record -> {
                    Auction auction = auctionMapper.selectById(record.getAuctionId());
                    if (auction == null) return false;
                    LocalDateTime auctionStartTime = LocalDateTime.parse(auction.getAuctionStartTime(), formatter);
                    LocalDateTime auctionEndTime = LocalDateTime.parse(auction.getAuctionEndTime(), formatter);
                    // 判断记录是否不是最高价且在有效拍卖时间范围内
                    return !highestRecordIds.contains(record.getId()) &&
                            auctionStartTime.isBefore(currentDateTime) &&
                            auctionEndTime.isAfter(currentDateTime);
                })
                .collect(Collectors.toList());

        if (nonHighestActiveRecords.isEmpty()) {
            return nonHighestActiveRecords; // 没有非最高记录则直接返回空列表
        }

        // 获取非最高记录中的所有用户ID和拍卖ID
        List<Integer> userIds = nonHighestActiveRecords.stream().map(AuctionRecord::getUserId).collect(Collectors.toList());
        List<Integer> auctionIds = nonHighestActiveRecords.stream().map(AuctionRecord::getAuctionId).collect(Collectors.toList());

        // 根据用户ID和拍卖ID分别查询用户和拍卖详情
        List<AuctionUser> users = auctionUserMapper.selectBatchIds(userIds);
        List<Auction> auctions = auctionMapper.selectBatchIds(auctionIds);

        // 将查询结果整合到拍卖记录中
        for (AuctionRecord record : nonHighestActiveRecords) {
            record.setUser(users.stream().filter(u -> u.getUserId() == record.getUserId()).findFirst().orElse(null));
            record.setAuction(auctions.stream().filter(a -> a.getAuctionId().equals(record.getAuctionId())).findFirst().orElse(null));
        }

        return nonHighestActiveRecords;
    }
}